import 'package:fl_chart/fl_chart.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sleep/config.dart';
import 'package:sleep/provider/wave_deatil_provider/wave_provider.dart';
import 'package:sleep/single/analyze/fatigue_analyze.dart';

import 'package:sleep/single/wave_show_model.dart';

class FatigueDetailWave {
  final String bf;
  final String bd;
  final String preclos;
  final FtaigueShowData? wave;
  final List<FtaigueShowData> waves;
  final List<FlSpot> dfSpots;
  final List<FlSpot> dbSpots;
  final List<FlSpot> preclosSpots;

  FatigueDetailWave({
    required this.bf,
    required this.bd,
    required this.preclos,
    required this.dfSpots,
    required this.dbSpots,
    required this.preclosSpots,
    required this.wave,
    required this.waves,
  });
}

final fatigueDetailProvider = Provider<FatigueDetailWave>((ref) {
  final fatigue = ref.watch(fatigueProvider);
  final analyze = fatigue.analyze as FatigueAnalyze;

  final wholeWave = analyze.showModel;
  final wholeWaves = analyze.waves;
  final df = wholeWave?.bf.toStringAsFixed(0) ?? "-";
  final bd = wholeWave?.bd.toStringAsFixed(2) ?? "-";
  final perclose = perclosToStr(wholeWave?.perclose);

  final List<FlSpot> dfSpots = [];
  final List<FlSpot> dbSpots = [];
  final List<FlSpot> preclosSpots = [];

  for (int i = 0; i < kDetialShowLengh; i++) {
    final index = wholeWaves.length - i - 1;
    if (index > 0) {
      final current = wholeWaves[index];

      final df = current.bf;
      final bd = current.bd;
      final perclose = current.perclose;
      final x = (kDetialShowLengh - i).toDouble();
      dfSpots.add(FlSpot(x, df));
      preclosSpots.add(FlSpot(x, perclose));
      dbSpots.add(FlSpot(x, bd));
    }
  }

  return FatigueDetailWave(
    wave: analyze.showModel,
    waves: analyze.waves,
    dfSpots: dfSpots,
    dbSpots: dbSpots,
    preclosSpots: preclosSpots,
    bf: df,
    bd: bd,
    preclos: perclose,
  );
});

perclosToStr(double? value) {
  if (value != null) {
    return '${(value).toStringAsFixed(0)}%';
  }
  return '-';
}
